package aburakc.smsweb.client;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import aburakc.smsweb.server.Sms;

public class SmsServlet extends HttpServlet {

	
	private Sms getFirstSms(){
		PersistenceManager pm = PMF.get().getPersistenceManager();	
		Sms retVal = null;
		Query query = pm.newQuery(Sms.class);
		query.setFilter("sent == false");
		query.setFilter("incomingMessage == false");
		query.setOrdering("date asc");
		try{
			List<Sms> restults = (List<Sms>)query.execute();
		}finally {
			query.closeAll();
		}
		
		return retVal;
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		//resp.getWriter().println("Hello, world");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Sms message;
		/*long lng = System.currentTimeMillis();
		Sms message = new Sms("123456789", "Mesaj", new Date(), (long)lng);
		Key key = KeyFactory.createKey(Sms.class.getSimpleName(), lng);
		message.setKey(key);
		pm.makePersistent(message);
		*/
		Query query = pm.newQuery(Sms.class);
		query.setFilter("sent == false");
		query.setFilter("incomingMessage == false");
		query.setOrdering("date asc");
		try{
			List<Sms> results = (List<Sms>)query.execute();
			if(results != null && results.size() > 0) {
				message = results.get(0);
				resp.getWriter().println(message.toNetworkMessage());
			}
		}finally {
			query.closeAll();
		}
		pm.close();
        
	}
}
